package com.cars.elasticsearch.handler;

import com.cars.elasticsearch.domain.DTO.ExceptionEnum;
import com.cars.elasticsearch.exception.EsException;
import com.cars.elasticsearch.http.response.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author: DT
 * @date: 2021/4/19 21:51
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     *
     * @param e 异常
     * @return {@code ResultResponse}
     */
    @ExceptionHandler(value = EsException.class)
    @ResponseBody
    public ResultResponse EsExceptionHandler(EsException e) {
        log.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return ResultResponse.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     *
     * @param e 异常
     * @return {@code ResultResponse}
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultResponse exceptionHandler(NullPointerException e) {
        log.error("发生空指针异常！原因是:", e);
        return ResultResponse.error(ExceptionEnum.BODY_NOT_MATCH);
    }

    /**
     * 处理主键重复的异常
     *
     * @param e 异常
     * @return {@code ResultResponse}
     */
    @ExceptionHandler(value = DuplicateKeyException.class)
    @ResponseBody
    public ResultResponse exceptionHandler(DuplicateKeyException e) {
        log.error("发生主键重复异常！原因是:", e);
        return ResultResponse.error(e.getMessage());
    }

    /**
     * 处理其他异常
     *
     * @param e 异常
     * @return {@code ResultResponse}
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultResponse exceptionHandler(Exception e) {
        log.error("未知异常！原因是:", e);
        return ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
    }
}